package com.card.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.card.entity.CardHolder;
import com.card.service.CardHolderService;
import com.card.utils.JwtUtils;
import com.card.utils.Result;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 名片夹
 */
@RestController
@RequestMapping("cardHolder")
public class CardHolderController extends ApiController {

    @Resource
    private CardHolderService cardHolderService;

    /**
     * 保存名片
     * @param id 对方名片id
     * @param request 请求头
     * @return
     */
    @GetMapping("saveCard")
    public Result<Void> saveCard(Long id, HttpServletRequest request) {
        String token = request.getHeader(JwtUtils.header);
        String openId = JwtUtils.validateToken(token);
        cardHolderService.saveCard(id, openId);
        return Result.success();
    }

    /**
     * 录入他人名片
     * @param cardHolder 对方名片信息
     * @param request 请求头
     * @return
     */
    @PostMapping("inputOtherCard")
    public Result<Void> InputOtherCard(@RequestBody CardHolder cardHolder, HttpServletRequest request) {
        String token = request.getHeader(JwtUtils.header);
        String openId = JwtUtils.validateToken(token);
        cardHolder.setCardInfoOpenId(openId);
        cardHolderService.save(cardHolder);
        return Result.success();
    }

    /**
     * 获取名片夹列表
     * @param keyword 搜索条件
     * @param request 请求头
     * @return
     */
    @GetMapping("getCardList")
    public Result<List<CardHolder>> getCardListCard(String keyword, HttpServletRequest request) {
        String token = request.getHeader(JwtUtils.header);
        String openId = JwtUtils.validateToken(token);
        LambdaQueryWrapper<CardHolder> cardHolderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        cardHolderLambdaQueryWrapper.eq(CardHolder::getCardInfoOpenId, openId);
        if (StringUtils.hasText(keyword)) {
            cardHolderLambdaQueryWrapper.like(CardHolder::getUserName, keyword)
                    .or().like(CardHolder::getCompany, keyword)
                    .or().like(CardHolder::getPhone, keyword);
        }
        cardHolderLambdaQueryWrapper.orderByDesc(CardHolder::getId);
        List<CardHolder> list = cardHolderService.list(cardHolderLambdaQueryWrapper);
        return Result.success(list);
    }
}

